<template>
    <BasicModal 
      :width="680"
      :height="320"
      :title="getModalTitle"
      okText="创建"
      wrapClassName="add-condition-modal-wrap"
      @visible-change="handleVisibleChange"
      @register="register"
      @cancel="cancelModal"
      @ok="okModal"
    >
        <div class="container">
            <div class="form">
                <a-form
                    ref="formRef"
                    :rules="formRules"
                    v-bind="formItemLayout"
                    name="advanced_search"
                    class="ant-advanced-search-form"
                    :model="formState"
                >
                    <a-form-item
                      label="条件名称"
                      name="conName"
                      :rules="[{ required: true, message: '请输入条件名称' }]"
                    >
                        <a-input v-model:value="formState.conName" placeholder="请输入条件名称"/>
                    </a-form-item>
                    <a-form-item
                        name="valueType"
                        style="width: 100%;"
                        :wrapperCol="{ span: 22 }"
                        :rules="[{ required: true, message: '请选择' }]"
                    >
                        <div class="valueType">
                            <div
                                class="valueTypeItem"
                                :class="formState.valueType === item.value && 'active'"
                                v-for="(item ,index) in ValueTypeOps"
                                @click="handleClickChange('valueType', item)"
                                :key="index"
                            >
                                {{  item.label }}
                            </div>
                        </div>
                    </a-form-item>
                    <a-form-item
                        label="数据来源"
                        name="dataSource"
                        :rules="[{ required: true, message: '请选择数据来源' }]"
                      >
                        <a-select
                          v-model:value="formState.dataSource" 
                          placeholder="请选择数据来源"
                          :options="DataSourceOps"
                        >
                        </a-select>
                      </a-form-item>
                      <template v-if="formState.valueType === ValueType.Enum">
                        <a-form-item
                          v-for="(listItem, index) in formState.valueInfoTemp"
                          :key="listItem.key"
                          v-bind="index === 0 ? {} : valueInfoLayout1"
                          :label="index === 0 ? '取值范围' : ''"
                          :name="['valueInfoTemp', index, 'value']"
                          :rules="{
                            required: true,
                            message: '请输入取值范围',
                            trigger: 'change',
                          }"
                        >
                          <a-input
                            v-model:value="listItem.value"
                            placeholder="请输入取值"
                            style="width: 60%; margin-right: 8px"
                          />
                          <MinusCircleOutlined
                            v-if="formState.valueInfoTemp.length > 1"
                            class="dynamic-delete-button"
                            @click="removeValueInfo(listItem)"
                          />
                          <PlusCircleOutlined
                            v-if="index === formState.valueInfoTemp.length - 1"
                            class="dynamic-delete-button"
                            @click="addValueInfo"
                          />
                        </a-form-item>
                        <!-- v-if=" index + 1 === valueInfoForm.valueInfo.length" -->
                        <!-- <a-form-item v-bind="ValueInfoFormItemLayout">
                          <a-button type="dashed" style="width: 60%" @click="addValueInfo">
                            <PlusOutlined />
                            Add field
                          </a-button>
                        </a-form-item> -->
                      </template>
                      <template v-if="formState.valueType === ValueType.Float">
                        <a-row>
                          <a-col :span="16">
                            <a-form-item
                              label="取值范围"
                              name="valueInfo"
                              :labelCol="{ span: 5 }"
                              :wrapperCol="{ span: 19 }"
                              :rules="{
                                required: true
                              }"
                            >
                              <a-row>
                                <a-col :span="11">
                                  <a-form-item
                                    name="valueInfoLeft"
                                  >
                                      <a-input-number v-model:value="formState.valueInfoLeft" style="width: 100%;" :controls="false" placeholder="请输入数值"/>
                                  </a-form-item>
                                </a-col>
                                <a-col :span="2" style="display: flex; justify-content: center;">
                                  -
                                </a-col>
                                <a-col :span="11">
                                  <a-form-item
                                    name="valueInfoRight"
                                  >
                                      <a-input-number v-model:value="formState.valueInfoRight" style="width: 100%;" :controls="false" placeholder="请输入数值"/>
                                  </a-form-item>
                                </a-col>
                              </a-row>
                            </a-form-item>
                          </a-col>
                          <a-col :span="8">
                            <a-form-item
                              label="单位"
                              name="unit"
                              :labelCol="{ span: 7 }"
                              :wrapperCol="{ span: 17 }"
                              :rules="[{ required: true, message: '请输入单位' }]"
                            >
                                <a-input v-model:value="formState.unit" placeholder="请输入单位"/>
                            </a-form-item>
                          </a-col>
                        </a-row>
                      </template>
                </a-form>
            </div>
        </div>
    </BasicModal>
</template>
<script lang="ts" setup>
import { inject, onMounted, computed, defineProps, watch, ref, reactive, defineEmits } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import ApiListOptions from '/@/api/type'
import { PageType, ValueType, ValueTypeOps, DataSource, DataSourceOps } from '/@/constants/job'
import {
  MinusCircleOutlined,
  PlusCircleOutlined
} from '@ant-design/icons-vue';
import type { Rule } from 'ant-design-vue/es/form';

const props = defineProps({
  pageType: {
    type: String,
    default: PageType.Add
  },
  conditionData: {  // 编辑时的数据
    
  }
});

interface valueInfoType {
  value: string;
  key: number;
}
interface FormState {
  conName: string;
  valueType: number;
  dataSource: number;
  valueInfo: string[] | number[];
  valueInfoTemp: valueInfoType[];
  valueInfoLeft: number | null;
  valueInfoRight: number | null;
  unit: string;
}
const formItemLayout = {
  labelAlign: 'left',
  labelCol: {
    xs: { span: 24 },
    sm: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 20 },
  },
}

const valueInfoLayout1 = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 24, offset: 0 },
    sm: { span: 20, offset: 4 },
  },
};

const baseFormState: FormState = {
  conName: '',
  valueType: ValueType.Enum,
  dataSource: DataSource.Api ,
  valueInfo: [],
  valueInfoTemp: [{value: '', key: Date.now()}], // 临时数据(渲染)
  valueInfoLeft: null,    // 临时数据(渲染)
  valueInfoRight: null,   // 临时数据(渲染)
  unit: '',
}

const formRef = ref()
const formState = ref<FormState>({...baseFormState})
// 表单校验
const leftPass = async (_rule: Rule, value: string) => {
  //console.log("leftPass--value", value)
  if (value === '') {
    return Promise.reject('请输入数值')
  } else if ( !!formState.value.valueInfoRight && Number(value || 0) > Number(formState.value.valueInfoRight || 0)) {
    return Promise.reject("不能大于右侧数值")
  } else {
    formRef.value.clearValidate("valueInfoRight")
    return Promise.resolve()
  }
}
const rightPass = async (_rule: Rule, value: string) => {
  //console.log("rightPass--value", value, typeof value)
  if (value === '') {
    return Promise.reject('请输入数值')
  } else if (!!formState.value.valueInfoLeft && Number(value || 0) < Number(formState.value.valueInfoLeft || 0)) {
    return Promise.reject("不能小于左侧数值")
  } else {
    formRef.value.clearValidate("valueInfoLeft")
    return Promise.resolve()
  }
}
const formRules: Record<string, Rule[]> = {
  valueInfoLeft: [{ required: true, message: '请输入数值', validator: leftPass, trigger: 'change' }],
  valueInfoRight: [{ required: true, message: '请输入数值', validator: rightPass, trigger: 'change' }],
}
const $http: ApiListOptions | undefined = inject('api')
const [register, { closeModal }] = useModalInner();
const emits = defineEmits(['success', 'register'])
const pageTypeList: any[] = [{
    type: PageType.Add,
    modalTitle: '新增条件'
  },{
    type: PageType.Edit,
    modalTitle: '编辑条件'
}]

const getModalTitle = computed((): string =>
    props.pageType ? pageTypeList.find(item => item.type === props.pageType).modalTitle : '新增条件'
)

const handleVisibleChange = async (visible) => {
    if(visible){
      if(props.pageType === PageType.Edit){
        formState.value = props.conditionData  as FormState
        const { valueType, valueInfo } = props.conditionData as FormState
        if(valueType === ValueType.Enum){
          formState.value.valueInfoTemp = valueInfo?.length ? valueInfo.map(item => {
            return {
              value: item,
              key: Date.now()
            }
          }) : [{
            value: '',
            key: Date.now()
          }]
        }else if(valueType === ValueType.Float){
          formState.value.valueInfoLeft = valueInfo[0] as number
          formState.value.valueInfoRight = valueInfo[1] as number
        }
      }else if(props.pageType === PageType.Add){

      }
    }
}

const handleClickChange = (type: string, item) => {
    switch(type){
      case 'valueType':
        {
          formState.value.valueType = item.value
        }
      break;  
    }
}

const removeValueInfo = (item: valueInfoType) => {
  const index = formState.value.valueInfoTemp.indexOf(item);
  if (index !== -1) {
    formState.value.valueInfoTemp.splice(index, 1);
  }
};

const addValueInfo = () => {
  formState.value.valueInfoTemp.push({
    value: '',
    key: Date.now()
  })
};

const okModal = () => {
    formRef.value.validate().then(async(formResult) => {
        //console.log("新建条件", formState.value)
        const formData: any = Object.assign({} , {...formState.value})
        const { valueType, valueInfoLeft, valueInfoRight, valueInfoTemp } = formState.value
        if(valueType === ValueType.Enum){
          formData.valueInfo = valueInfoTemp.map(item => item.value)
        }else if(valueType === ValueType.Float){
          formData.valueInfo = [valueInfoLeft, valueInfoRight]
        }
        formData.valueInfoTemp = undefined
        formData.valueInfoLeft = undefined
        formData.valueInfoRight = undefined
        //console.log("新建条件--提交接口", formData)
        if(props.pageType === PageType.Add){
          const res = await $http?.postConditionSave({ ...formData })
          const { data } = res
          if(data.code === 200){
            cancelModal()
          }
        }else if(props.pageType === PageType.Edit){
          const res2 = await $http?.postConditionUpdate({ ...formData })
          const { data } = res2
          if(data.code === 200){
            cancelModal()
          }
        }
      }).catch(err => {
      console.log("新建/编辑条件报错", err)
    })
}

const cancelModal = () => {
  //console.log("关闭弹框")
  formState.value = baseFormState
  formRef.value.resetFields()
  emits('success')
  closeModal();
}

</script>
<style lang="less" scoped>
.container{
    padding: 0 20px;
    height: 300px;
    overflow-y: scroll;
    .form{
        margin-top: 10px;
        width: 100%;
        .valueType{
            display: flex;
            .valueTypeItem{
                width: 91px;
                height: 30px;
                line-height: 30px;
                margin-right: 10px;
                background: #F8F8F8;
                border-radius: 15px;
                text-align: center;
                &.active{
                  color: #fff;
                    background: linear-gradient(315deg, #30AEF2 0%, #167DB5 100%);
                }
            }
        }
        .dynamic-delete-button {
          cursor: pointer;
          position: relative;
          top: 4px;
          font-size: 24px;
          color: #999;
          transition: all 0.3s;
        }
        .dynamic-delete-button:hover {
          color: #777;
        }
        .dynamic-delete-button[disabled] {
          cursor: not-allowed;
          opacity: 0.5;
        }
    }
}
</style>
<style lang="less">
    .add-condition-modal-wrap {
      .ant-modal-content{
        .ant-modal-header{
          background: linear-gradient(135deg, #073451 0%, #0B4C68 100%);
          .jeecg-basic-title{
            color: #fff;
          }
        }
        .ant-modal-close-x{
          color: #fff;
        }
        // .ant-modal-body{
        //   .ant-form-item.ant-form-item-with-help{
        //     margin-bottom: 36px !important;
        //   }
        // }
      }
    }
  </style>